class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {

        int m = matrix.size(), n = matrix[0].size();

        vector<vector<int>> dp(m + 2, vector<int>(n + 2, 10000));

        for (int i = 1; i <= n; i++)
            dp[1][i] = matrix[0][i - 1];

        for (int i = 2; i <= m; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                dp[i][j] = min(min(dp[i - 1][j], dp[i - 1][j - 1]), dp[i - 1][j + 1]) + matrix[i - 1][j - 1];
            }
        }

        int res = 0x3f3f3f3f;
        for (int i = 1; i <= n; i++)
            res = min(res, dp[m][i]);

        return res;
    }
};